<template>
  <div>
    <el-card>
      <el-button type="primary" circle @click="openDig(null)"
        >添加角色</el-button
      >
    </el-card>
    <!-- 用户展示区域 -->
    <el-card>
      <el-table :data="roleList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="角色名" width="180">
        </el-table-column>
        <el-table-column prop="remark" label="描述" width="180">
        </el-table-column>
        <el-table-column prop="remark" label="系统必要角色" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.default"
              ><el-tag effect="dark">是</el-tag></span
            >
            <span v-else><el-tag type="warning" effect="dark">否</el-tag></span>
          </template>
        </el-table-column>

        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="openDig(scope.row.id)"
              >修改权限</el-button
            >
            <el-button
              type="text"
              size="small"
              color="red"
              @click="deleteRoleById(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-size="pageSize"
      layout="total,  prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="roleForm.remark"></el-input>
        </el-form-item>

        <el-form-item label="权限分配">
          <el-tree
            :data="permissionList"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            ref="tree"
            highlight-current
            :auto-expand-parent="flase"
          ></el-tree>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveRole()">确定</el-button>
          <el-button @click="close()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style>
.top_input {
  margin: 4px;
}
</style>

<script>
import roleApi from "@/api/role";
import permissionApi from "@/api/permission";
export default {
  data() {
    return {
      roleList: [],
      permissionList: [],
      pageSize: 10,
      pageNo: 1,

      total: 0,

      // 对话框标题
      title: "",
      dialogVisible: false,

      roleForm: {},

      defaultProps: {
        children: "children",
        label: "label",
      },

      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        permission: [
          { required: true, message: "请选择角色权限", trigger: "change" },
        ],
      },
      loading: false,
    };
  },

  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.close();
        })
        .catch((_) => {});
    },

    close() {
      this.roleForm = {};
      this.dialogVisible = false;
      this.$refs.tree.setCheckedKeys([]);
    },

    // 分页
    handleCurrentChange(val) {
      if (val != undefined || val != null) {
        this.pageNo = val;
      }
      this.getUsers();
    },
    getRoleList() {
      this.loading = true;
      roleApi.getRoleList(this.pageNo, this.pageSize).then((resp) => {
        this.roleList = resp.data.roles;

        this.total = resp.data.total;
        this.loading = false;
      });
    },

    getPermissionApiList() {
      this.loading = true;
      permissionApi
        .getPermissionList(this.pageNo, this.pageSize)
        .then((resp) => {
          // /* 把原始数据转成 el-tree 需要的格式 */
          this.permissionList = Object.keys(resp.data).map((levelName) => ({
            id: levelName, // 一级节点 id
            label: levelName, // 一级节点显示文字
            children: resp.data[levelName].map((item) => ({
              id: item.id,
              label: item.remark, // 二级节点显示
            })),
          }));
          this.loading = false;
        });
    },
    openDig(id) {
      if (id) {
        this.title = "修改角色信息";
        this.loading = true;
        // 回显数据
        roleApi.getById(id).then((resp) => {
          this.roleForm = resp.data.role;

          const nodes = [];
          resp.data.permissions.forEach((node, index) => {
            if (node.children == null) {
              nodes.push({
                id: node.id,
                label: node.remark,
              });
            }
          });

          this.$refs.tree.setCheckedNodes(nodes);
          this.loading = false;
        });
      } else {
        this.title = "添加角色信息";
      }
      this.dialogVisible = true;
    },

    saveRole() {
      console.log(this.roleForm);
      this.$refs["roleForm"].validate((valid) => {
        if (valid) {
          const checkNodes = this.$refs.tree.getCheckedNodes();
          const permissions = [];

          checkNodes.forEach((node, index) => {
            if (node.children == null) {
              permissions.push(node.id);
            }
          });
          this.loading = true;
          roleApi
            .save(this.roleForm, permissions)
            .then((resp) => {
              this.$message({
                message: resp.message,
                type: "success",
              });
              this.getRoleList();

              this.close();
              this.loading = false;
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          this.loading = false;
          return false;
        }
      });
    },

    deleteRoleById(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          roleApi
            .deleteById(id)
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });

              this.getRoleList();
              this.loading = false;
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },

  created() {
    this.getRoleList();

    this.getPermissionApiList();
  },
};
</script>
